package edu.tgc.web.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.octo.captcha.service.image.ImageCaptchaService;

public class CaptchaController {

    public static final String CAPTCHA_IMAGE_FORMAT = "jpeg";

    @Autowired
    protected ImageCaptchaService captchaService;

    @ResponseBody
    @RequestMapping(value = "captcha")
    public void captcha(HttpServletResponse response, HttpServletRequest request, HttpSession session) {
        String sessionId = session.getId();
        System.out.println(sessionId);
        BufferedImage challenge = this.captchaService.getImageChallengeForID(sessionId, request.getLocale());
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(challenge, CaptchaController.CAPTCHA_IMAGE_FORMAT, jpegOutputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/" + CaptchaController.CAPTCHA_IMAGE_FORMAT);

        ServletOutputStream responseOutputStream;
        try {
            responseOutputStream = response.getOutputStream();
            responseOutputStream.write(jpegOutputStream.toByteArray());
            responseOutputStream.flush();
            responseOutputStream.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

    }
}
